import config from '../config.js';
let header;
let isLogin=false;
const http = (params) => {
  return new Promise((resole, reject) => {
    wx.getStorage({
      key: 'token',
      success: function(res) {
        header={
          "Content-Type": "application/json",
          "token": res.data
        }
      },
      complete(){
        wx.request({
          url: config.apiHost + params.url,
          data: params.data,
          header: params.header || header,
          method: params.method || 'GET',
          dataType: params.dataType,//返回的数据格式,默认为JSON，特殊格式可以在调用的时候传入参数16      
          responseType: params.responseType,//响应的数据类型
          success(res) {
            if (res.statusCode === 200) {
              if (res.data.code=='401'){
                if (!isLogin){
                  isLogin=true;
                  wx.navigateTo({
                    url: `/pages/login/login`,
                  })
                }
              } else if (res.data.code == '500'){
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  duration: 2000
                })
              }
              resole(res.data);
            } else {
              let errMag = res.data.message;
              console.log(errMag);
            }
          },
          fail: function (e) {
            console.log(e);
            reject(e);
          }
        })
      }
    })
  
  })
}
const httpFormData = (params) => {
  return new Promise((resole, reject) => {
    wx.getStorage({
      key: 'token',
      success: function (res) {
        header = {
          "Content-Type": "multipart/form-data",
          "token": res.data
        }
      },
      complete() {
        wx.uploadFile({
          url: config.apiHost + params.url,
          filePath: params.filePath,
          name: 'file',
          formData: params.formData,
          header,
          success(res) {  
            resole(res.data)
          },
          fail(error){
            reject(e);
          }})
      }
    })
  })
}
module.exports = {
   http,
  httpFormData,
}

